package dbTest.Manticore

import com.manticoresearch.client.ApiClient
import com.manticoresearch.client.Configuration
import com.manticoresearch.client.api.IndexApi
import com.manticoresearch.client.api.SearchApi
import com.manticoresearch.client.api.UtilsApi
import com.manticoresearch.client.model.*

class ManticoreClient(host: String = "localhost", port: Int = 9308) {
    private val client: ApiClient = Configuration.getDefaultApiClient()
    private val indexApi: IndexApi
    private val searchApi: SearchApi
    private val utilsApi: UtilsApi

    init {
        client.setBasePath("http://$host:$port")
        indexApi = IndexApi(client)
        searchApi = SearchApi(client)
        utilsApi = UtilsApi(client)
    }

    /**
     * 创建表
     */
    fun createTable(tableName: String, fields: Map<String, String>): Boolean {
        val fieldDefinitions = fields.entries.joinToString(", ") { "${it.key} ${it.value}" }
        val sql = "CREATE TABLE $tableName ($fieldDefinitions)"
        
        try {
            val result = utilsApi.sql(sql, true)
            println("Table created: $result")
            return true
        } catch (e: Exception) {
            println("Error creating table: ${e.message}")
            return false
        }
    }

    /**
     * 删除表
     */
    fun dropTable(tableName: String): Boolean {
        val sql = "DROP TABLE $tableName"
        
        try {
            val result = utilsApi.sql(sql, true)
            println("Table dropped: $result")
            return true
        } catch (e: Exception) {
            println("Error dropping table: ${e.message}")
            return false
        }
    }

    /**
     * 插入文档
     */
    fun insertDocument(tableName: String, doc: Map<String, Any>, id: Long? = null): Boolean {
        val insertRequest = InsertDocumentRequest()
        insertRequest.index(tableName)
        insertRequest.setDoc(doc)
        id?.let { insertRequest.setId(it) }
        
        try {
            val result = indexApi.insert(insertRequest)
//            println("Document inserted: $result")
            return true
        } catch (e: Exception) {
            println("Error inserting document: ${e.message}")
            return false
        }
    }

    /**
     * 替换文档（如果存在则更新，否则插入）
     */
    fun replaceDocument(tableName: String, id: Long, doc: Map<String, Any>): Boolean {
        val replaceRequest = InsertDocumentRequest()
        replaceRequest.index(tableName)
        replaceRequest.setId(id)
        replaceRequest.setDoc(doc)
        
        try {
            val result = indexApi.replace(replaceRequest)
            println("Document replaced: $result")
            return true
        } catch (e: Exception) {
            println("Error replacing document: ${e.message}")
            return false
        }
    }

    /**
     * 更新文档
     */
    fun updateDocument(tableName: String, id: Long, doc: Map<String, Any>): Boolean {
        val updateRequest = UpdateDocumentRequest()
        updateRequest.index(tableName)
        updateRequest.setId(id)
        updateRequest.setDoc(doc)
        
        try {
            val result = indexApi.update(updateRequest)
            println("Document updated: $result")
            return true
        } catch (e: Exception) {
            println("Error updating document: ${e.message}")
            return false
        }
    }

    /**
     * 删除文档
     */
    fun deleteDocument(tableName: String, id: Long): Boolean {
        val deleteRequest = DeleteDocumentRequest()
        deleteRequest.index(tableName)
        deleteRequest.setId(id)
        
        try {
            val result = indexApi.delete(deleteRequest)
            println("Document deleted: $result")
            return true
        } catch (e: Exception) {
            println("Error deleting document: ${e.message}")
            return false
        }
    }

    /**
     * 搜索文档
     */
    fun searchDocuments(tableName: String, queryString: String? = null, limit: Int = 20): SearchResponse? {
        val searchRequest = SearchRequest()
        searchRequest.index(tableName)
        
        if (queryString != null) {
            val query = HashMap<String, Any>()
            query["query_string"] = queryString
            searchRequest.setQuery(query)
        }
        
        searchRequest.setLimit(limit)
        
        try {
            val result = searchApi.search(searchRequest)
            return result
        } catch (e: Exception) {
            println("Error searching documents: ${e.message}")
            return null
        }
    }

    /**
     * 执行SQL查询
     */
    fun executeSql(sql: String): Any? {
        try {
            val result = utilsApi.sql(sql, true)
            return result
        } catch (e: Exception) {
            println("Error executing SQL: ${e.message}")
            return null
        }
    }
}
